<template>
    <div>
        <div v-if="limit == 1">
            <el-upload
                class="uploader"
                :action="domain"
                :data="QiniuData"
                :on-error="uploadError"
                :on-success="uploadSuccess"
                :before-remove="beforeRemove"
                :before-upload="beforeAvatarUpload"
                :show-file-list="false">
                    <img v-if="uploadPicUrl" :style="{height:height/3.58+'px'}"  :src="uploadPicUrl" ref="singleUpload" class="singleUpload">
                    <div v-else>
                        <img class="tianjia" src="../../assets/img/tianjia2.png" />
                        <p class="uploader-icons uploader-iconsNew">上传</p>
                        <p class="font">尺寸750*{{height}}px</p>
                        <p class="font">支持jpg,png格式，图片大小不超过1M</p>
                    </div>
            </el-upload>
            <div class="uploadFont">
                <div class="xing">*</div>
            </div>
        </div>
        <div v-else class="multImg_content" :style="{'height':height}">
            <div  v-for="(item,index) in imgList" class="imgWapper" v-if="imgList.length" :key=index>
                <img class="pic-box" ref="picBox" :src="item.fileUrl" >
                <img src="../../assets/img/shanchu.png" class="delImg" @click="removeImg(item,index)" />
            </div>
            <el-upload
                ref="upload"
                class="uploader"
                :action="domain"
                :data="QiniuData"
                :on-remove="handleRemove"
                :on-error="uploadError"
                :on-success="uploadSuccess"
                :before-remove="beforeRemove"
                :before-upload="beforeAvatarUpload"
                multiple
                :limit="remianLImit"
                :on-exceed="handleExceed"
                :show-file-list="false"
                :file-list="fileList">
                    <img class="tianjia tianjiaNew" src="../../assets/img/tianjia2.png" />
                    <p class="uploader-icons">上传</p>
                    <p class="font">尺寸750*{{height}}px</p>
                    <p class="font">支持jpg,png格式，每张图不超过1M，可上传{{limit}}张图片</p>
            </el-upload>
             <div class="uploadFont">
                <div class="xing">*</div>
            </div>
        </div>
    </div>
</template>
<script>
import api from '@/fetch/url.js';
export default {
    props:{
        limit:{
            type:Number,
            default:1,
        },
        dataOther:{
            type:Array,
            default:() =>{
                return []
            }
        },
        dataHome:{
            type:Object,
            default:() =>{
                return {}
            }
        },
        height:{
            type:Number,
        },
    },
    data(){
        return{
            remianLImit:0,
            QiniuData: {
                key: "", //图片名字处理
                token: "" //七牛云token
            },
            bucket:'sojour',
            domain: "https://upload-z1.qiniup.com", // 七牛云的上传地址（华北区）
            qiniuaddr: "https://cdn.yueyangshuyuan.com", // 七牛云的图片外链地址 你的七牛云里配置有
            uploadPicUrl: "", //提交到后台图片地址
            fileList: [],
            imgList:[],
            nowTime:'',
            fileExtension:'',//文件后缀名
            oneFlag:true,
            isUpladingUrl:{
                width:0,
                height:0
            },
        }
    },
    watch: {
        dataHome(newVal, oldValue){
            if(this.dataHome.fileUrl){
                this.uploadPicUrl = this.dataHome.fileUrl;
            }else{
                this.uploadPicUrl = `${this.qiniuaddr}/${this.dataHome.name}`;
            }
        },
        dataOther(newVal, oldValue){
            this.imgList = [];
            this.dataOther.length>0&&this.dataOther.forEach(item => {
                if(item.fileUrl){
                    this.imgList.push({
                       fileUrl: item.fileUrl,
                       id:item.id
                    })
                }else{
                    this.imgList.push({
                        fileUrl: `${this.qiniuaddr}/${item.name}`,
                        id:0
                    })
                }
            });
            // this.oneFlag && (this.remianLImit = this.limit - this.imgList.length,this.oneFlag=false);
            
            console.log(this.remianLImit,'remianLImit')
        }
    },
    created(){
        api.upToken({
            accessKey:'i5zelMCxFeu45ob45iFOBdWPvOTraza1wXvWAg73',
            secretKey:'leGRrXl_Kr5aXuxKQ7laa6jrZvzxgs6LGeOCfrxW',
            bucket:this.bucket
        }).then(json=>{
            this.QiniuData.token = json;
        })
    },
    mounted(){
        //this.height
        // console.log(this.$refs.singleUpload);
        // this.$refs.upload.height=this.height+"px";
        // this.$refs.singleUpload.height=this.height+"px";
        // this.$refs.picBox.height=this.height+"px";
    },
    methods:{
        removeImg(item,index){
            this.$refs.upload.uploadFiles = [];
            this.imgList.splice(index,1);
            this.remianLImit = this.limit - this.imgList.length;
            this.$emit('uploadHandler',index,-1);
        },
        handleRemove(file, fileList) {
            this.uploadPicUrl = "";
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 ${this.limit}张图片，如需更换，请删除上一张图片在重新选择！`
            );
        },
        beforeAvatarUpload(file) {
            if(this.imgList.length >= this.limit){
                this.$message.warning(
                    `当前限制选择 ${this.limit}张图片，如需更换，请删除上一张图片在重新选择！`
                );
                return false;
            }
            const isPNG = file.type === "image/png";
            const isJPEG = file.type === "image/jpeg";
            const isJPG = file.type === "image/jpg";
            const isLt2M = file.size / 1024 / 1024 < 1;
            if (!isPNG && !isJPEG && !isJPG) {
                this.$message.error("上传头像图片只能是 jpg、png、jpeg 格式!");
                return false;
            }
            if (!isLt2M) {
                this.$message.error("上传头像图片大小不能超过 1MB!");
                return false;
            }
            let width = 750;
            let height = this.height;
            let _URL = window.URL || window.webkitURL;         
            let img = new Image();
            let _this = this;
            // img.src = `${this.qiniuaddr}/yuyang_${this.getDate()}${file.name}`;
            img.addEventListener('load' , function(){
                _this.isUpladingUrl.width = img.width;
                _this.isUpladingUrl.height = img.height;
                if(img.width !== width || img.height !== height){
                    _this.$message.error('上传的图片尺寸必须是750*'+_this.height+'!');
                    return false;
                }
            },false);
            img.src = _URL.createObjectURL(file);
            this.fileExtension = file.name.split(".").pop();
            this.QiniuData.key = `yuyang_${this.getDate()}${file.name}`;
        },
        uploadSuccess(response, file, fileList) {
            let data = {
                bucket:this.bucket,
                fileKey:response.hash,
                name:response.key
            }
            console.log(this.isUpladingUrl)
            // if(this.isUpladingUrl.width == 750 && this.isUpladingUrl.height == this.height){
                this.$emit('uploadHandler',data,this.limit);
            // }
            // this.uploadPicUrl = `${this.qiniuaddr}/${response.key}`;
            // this.imgList.push(this.uploadPicUrl);
        },
        uploadError(err, file, fileList) {
            if(JSON.parse(err.message).error == 'file exists'){
                this.$message({
                    message: "文件已存在！",
                    type: "error",
                    center: true
                });
            }else{
                this.$message({
                    message: "上传出错，请重试！",
                    type: "error",
                    center: true
                });
            }
        },
        beforeRemove(file, fileList) {
            // return this.$confirm(`确定移除 ${ file.name }？`);
        },
        //以下是时间戳函数
        getDate(){
            var myDate = new Date();
            //获取当前年
            var year = myDate.getFullYear();
            //获取当前月
            var month = myDate.getMonth() + 1;
            //获取当前日
            var date = myDate.getDate();
            var h = myDate.getHours(); //获取当前小时数(0-23)
            var m = myDate.getMinutes(); //获取当前分钟数(0-59)
            var s = myDate.getSeconds();
            //获取当前时间
            var now = year + '_' + this.conver(month) + "_" + this.conver(date) + "_" + this.conver(h) + '_' + this.conver(m) + "_" + this.conver(s);
            return now;
        },
        conver(s) {
            return s < 10 ? '0' + s : s;
        },
    }
}
</script>
<style lang="scss">
    .uploader{
        float: left;
        width:220px;
        height:160px;
        background: #F7F7F9;
        border-radius: 2px;
        cursor: pointer;
    }
    .uploadFont {
        float: left;
        margin-left:10px;
        .xing {
            font-size: 16px;
            color:#F52D2D;
        }
    }
    .el-upload {
        width:220px;
        height:160px;
        padding:0 5px;
        box-sizing: border-box;
        font-size: 14px;
        background: #F7F7F9;
        border-radius: 2px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        /* background: #F7F7F9; */
        border-radius: 2px;
        border: none;
    }
    .uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .uploader-icons {
        font-style: normal;
        text-align: center;
        color: #777777;
        margin-top:5px;
        margin-bottom:10px;
    }
    .uploader-iconsNew {
        margin-bottom:20px;
    }
    .font ,.font-type{
        font-size: 12px;
        color: #A9A9A9;
        text-align: center;
        line-height:20px;
    }
    .tianjia {
        margin:20px 88px 0;
    }
    // .tianjiaNew {
    //      margin:15px 88px 0;
    // }
    .singleUpload ,.pic-box{
        width: 220px;
        height: 160px;
        display: block;
        // object-fit: cover;
        border-radius: 4px;
        position: absolute;
        top:50%;
        -webkit-transform:translate(0%,-50%);
		transform:translate(0%,-50%);
    }
    .multImg_content{
       display: flex;
       flex-wrap:wrap;
    }
    .imgWapper{
        margin-right: 10px;
        position: relative;
        width: 220px;
        height:160px;
        margin-bottom:10px;
    }
    .delImg{
        position: absolute;
        top: 0;
        right: 0;
        z-index:9;
        // color: #ccc;
        cursor: pointer;
    }
</style>

